package wiki.zimo.servlet.reception;

import wiki.zimo.constant.Constant;
import wiki.zimo.dao.CategoryDao;
import wiki.zimo.dao.Dao;
import wiki.zimo.dao.ProductDao;
import wiki.zimo.domain.Category;
import wiki.zimo.domain.Product;
import wiki.zimo.servlet.BaseServlet;
import wiki.zimo.utils.JsonUtils;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;
import java.util.List;

/**
 * @version v1.0
 * @auther: 子墨
 * @datetime: 2018/11/1 16:56
 * @description: 处理首页的轮播图，分类目录，最新，热门商品的展示的Servlet
 */
@WebServlet(value = "/index")
public class IndexServlet extends BaseServlet {

    Dao cDao = new CategoryDao();
    ProductDao pDao = new ProductDao();

    /**
     * @auther: 子墨
     * @date: 2018/11/1 22:15
     * @describe: 首页
     * @param: [request, response]
     * @return: java.lang.String
     * @version v1.0
     */
    @Override
    public String index(HttpServletRequest request, HttpServletResponse response) throws Exception {
        HttpSession session = request.getSession();

        // 商品分类
        List<Category> categorys = cDao.findAll();
        session.setAttribute(Constant.CATEGORYS, categorys);

        // 最新商品
        List<Product> newestProduct = pDao.findNewestProducts();
        session.setAttribute(Constant.PRODUCT_NEWEST, newestProduct);

        // 最热商品
        List<Product> hotestProduct = pDao.findHotestProducts();
        session.setAttribute(Constant.PRODUCT_HOTEST, hotestProduct);

        return super.index(request, response);
    }

    /**
     * @auther: 子墨
     * @date: 2018/11/1 20:51
     * @describe: 得到所有商品分类的json数据接口
     * @param: [request, response]
     * @return: java.lang.String
     * @version v1.0
     */
    public String getAllCategory(HttpServletRequest request, HttpServletResponse response) {
        response.setContentType("text/html;charset=utf-8");
        try {
            List<Category> list = cDao.findAll();
            String json = JsonUtils.listToJson(list);
            PrintWriter writer = response.getWriter();
            writer.print(json);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
